<template>
  <div>
    <div class="top">
      <div class="top-op">
        <el-button type="default" @click="back">
          <span class="iconfont icon-right" style="transform: rotate(180deg);"></span>
          返回
        </el-button>
        <div class="file-title" v-if="baseFile && baseFile.fileName">
          <span class="iconfont icon-clock" style="margin-left: 12px;"></span>
          {{ baseFile.fileName }} 的历史版本
        </div>
        <div class="iconfont icon-refresh" @click="loadDataList" style="margin-left: auto"></div>
      </div>
    </div>

    <div class="file-list" v-if="tableData.list && tableData.list.length > 0">
      <Table
        ref="dataTableRef"
        :columns="columns"
        :dataSource="tableData"
        :fetch="loadDataList"
        :initFetch="false"
        :options="tableOptions"
        @rowSelected="rowSelected"
      >
        <template #fileName="{ index, row }">
          <div class="file-item" @mouseenter="showOp(row)" @mouseleave="cancelShowOp(row)">
            <template v-if="(row.fileType == 3 || row.fileType == 1) && row.status == 2">
              <Icon :cover="row.fileCover" :width="32"></Icon>
            </template>
            <template v-else>
              <Icon v-if="row.folderType == 0" :fileType="row.fileType"></Icon>
              <Icon v-if="row.folderType == 1" :fileType="0"></Icon>
            </template>
            <span class="file-name" :title="row.fileName">
              <span @click="preview(row)">{{ row.fileName }}</span>
<!--              <span v-if="row.status == 0" class="transfer-status">转码中</span>-->
<!--              <span v-if="row.status == 1" class="transfer-status transfer-fail">转码失败</span>-->
            </span>
            <span class="op">
              <template v-if="row.showOp && row.fileId && row.status == 2">
                <span class="iconfont icon-share1" @click="share(row)">分享</span>
                <span class="iconfont icon-download" v-if="row.folderType == 0" @click="download(row)">下载</span>
                <span class="iconfont icon-del" @click="delFile(row)">删除</span>
                <span class="iconfont icon-revert" @click="restore(row)">还原</span>
              </template>
            </span>
          </div>
        </template>
        <template #fileSize="{ index, row }">
          <span v-if="row.fileSize">{{ proxy.Utils.size2Str(row.fileSize) }}</span>
        </template>
      </Table>
    </div>
    <div class="no-data" v-else>
      <div class="no-data-inner">
        <Icon iconName="no_data" :width="120" fit="fill"></Icon>
        <div class="tips">暂无历史版本</div>
      </div>
    </div>

    <ShareFile ref="shareRef"></ShareFile>
    <Preview ref="previewRef"></Preview>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import Table from "@/components/Table.vue";
import ShareFile from "./ShareFile.vue";
const { proxy } = getCurrentInstance();

const route = useRoute();
const router = useRouter();
const baseFileId = ref(route.params.fileId);
const baseFile = ref({});

const api = {
  history: "/file/history/", // + fileId
  restoreHistory: "/file/restoreHistory",
  delFile: "/file/delFile",
  createDownloadUrl: "/file/createDownloadUrl",
  download: "/api/file/download",
};

const columns = [
  { label: "文件名", prop: "fileName", scopedSlots: "fileName" },
  { label: "修改时间", prop: "lastUpdateTime", width: 200 },
  { label: "大小", prop: "fileSize", scopedSlots: "fileSize", width: 200 },
];

const tableData = ref({ list: [] });
const tableOptions = ref({ extHeight: 50, selectType: "checkbox" });

const loadDataList = async () => {
  if (!baseFileId.value) return;
  const result = await proxy.Request({ url: api.history + baseFileId.value, showLoading: true });
  if (!result) return;
  // history list has no pagination in backend; wrap to table data
  tableData.value = { list: result.data, pageNo: 1, pageSize: result.data.length, totalCount: result.data.length };
  // set base file name from first item originalName if present or from route query
  if (!baseFile.value.fileName && result.data && result.data.length > 0) {
    baseFile.value = result.data[0].baseFile || {}; // in case backend returns baseFile
  }
};

const showOp = (row) => {
  (tableData.value.list || []).forEach((e) => (e.showOp = false));
  row.showOp = true;
};
const cancelShowOp = (row) => (row.showOp = false);
const rowSelected = () => {};

const shareRef = ref();
const share = (row) => {
  shareRef.value.show(row);
};

// 预览
const previewRef = ref();
const preview = (data) => {
  // 目录（历史版本一般为文件，但做保护）
  if (data.folderType == 1) {
    return;
  }
  // if (data.status != 2) {
  //   proxy.Message.warning("文件未完成转码, 无法预览");
  //   return;
  // }
  previewRef.value.showPreview(data, 0);
};

const download = async (row) => {
  const result = await proxy.Request({ url: api.createDownloadUrl + "/" + row.fileId });
  if (!result) return;
  window.location.href = api.download + "/" + result.data;
};

const delFile = (row) => {
  proxy.Confirm(`你确定要删除【${row.fileName}】吗? 删除的文件可在10天内通过回收站还原`, async () => {
    const result = await proxy.Request({ url: api.delFile, params: { fileIds: row.fileId } });
    if (!result) return;
    loadDataList();
  });
};

const restore = async (row) => {
  proxy.Confirm(`确定将该历史版本还原为最新版本吗？`, async () => {
    const result = await proxy.Request({ url: api.restoreHistory, params: { fileId: row.fileId } });
    if (!result) return;
    proxy.Message.success("已还原为最新版本");
    // 返回主文件目录或刷新
    back();
  });
};

const back = () => {
  router.back();
};

onMounted(() => {
  loadDataList();
});
</script>

<style lang="scss" scoped>
.top {
  .top-op {
    display: flex;
    align-items: center;
  }
  .file-title {
    font-size: 14px;
    color: #666;
  }
}
@import "@/assets/file.list.scss";
</style>
